package com.xc.freeapp.account.controller;

import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.xc.freeapp.bean.AuthInfo;
import com.xc.freeapp.exception.BaseException;
import com.xc.freeapp.util.AuthUtil;
import com.xc.freeapp.util.Constant;
import com.xc.freeapp.util.QiniuUpload;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

/**
 * 七牛上传云存储
 * @author ZhouXinjie
 */
@Controller
@RequestMapping("/upload")
@Api(value="/upload",description="七牛上传")
public class UploadController extends AbstractController{
	private Logger log = Logger.getLogger(this.getClass());
	/**
	 * 获取上传下载凭证
	 * */
	@RequestMapping(value = "/uploadToken", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "获取上传下载凭证")
	public  Map<String, Object> uploadToken()throws BaseException{
		AuthInfo authInfo = AuthUtil.getAuthInfo(getRequest());
		Map<String, Object> map = new HashMap<String, Object>();
		String upToken = QiniuUpload.getUpToken0();
		map.put("upToken", upToken);
		log.info(authInfo.getAppId()+"------------upToken-----------"+upToken);
		return map;
	};
	/**
	 * 文件上传
	 *
	 * @param request upToken
	 */
	@RequestMapping(value = "uploadImage", method = RequestMethod.POST)
	@ResponseBody
	public List<String> uploadImage(HttpServletRequest request) throws BaseException {
		AuthInfo authInfo = AuthUtil.getAuthInfo(getRequest());
		String type=(String) request.getParameter("imgtype");   // imgtype
		String appId=authInfo.getAppId();
		Integer appIdInt = 0;
		if(StringUtils.isNotBlank(appId)){
			if(NumberUtils.isNumber(appId)){
				appIdInt=Integer.valueOf(appId);   // appid
			}
		}
		String token = request.getParameter("token");
		try {
			String upToken = QiniuUpload.getUpToken0();
			List<String> list = QiniuUpload.uploadRequestFiles(request, upToken);
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			throw  new BaseException(Constant.COMMON_ERROR);
		}

	}

}
